
require('./sporting.less')
require('../../assets/fonts/iconfont.css')

// 引入文档加载事件，dom选择器封装
let { $, $$, $$$ } = require('../../utils/dom')
//引入axios
const axios = require('../../utils/axios')


$(function () {


    /* 计算配速函数 
    d： 距离
    s： 时间
    */
    function calcPace(d, s) {
        let distance = d
        let spendTime = s / 60
        if (distance > 0 && spendTime > 0) {
            let pace = parseFloat(spendTime / distance)
            let m = Math.floor(pace)
            let s = ((pace - m) * 60).toFixed(0)
            return `${m}'${s}"`
        }
        return "--"
    }

    /* 计算卡路里 */
    function calCalorie(miles) {
        if (miles > 0) {
            let calorie = 60 * miles * 1.036;
            return calorie.toFixed(2)
        }
        return "--"
    }


    /**
     * 运动函数
     */
    function running() {
        ++t; //总秒数
        let h = Math.floor(t / 3600);
        let m = Math.floor(t / 60) % 60;
        let s = t % 60;

        $$('#timebox').textContent = [h, m, s].map(function (v) {
            return v < 10 ? '0' + v : v
        }).join(':')
        let d = $$('#kilometre').textContent = (t * 2 / 1000).toFixed(2)
        $$('#pace').textContent = calcPace(d, t)

        $$('#calorie').textContent = calCalorie(d)


    }


    /**
     * 用时 & 路程
     */
    let t = 0; //用时数 unit: s
    let timer = setInterval(running, 1000)


    /**
     * 暂停
     */
    $$('.pausebtn').addEventListener('click', function () {
        this.style.display = 'none'
        $$('.continuebtn').style.display = 'flex';
        $$('.stopbtn').style.display = 'flex';

        //关闭计时器
        clearInterval(timer)

    })

    /**
     * 继续
     */
    $$('.continuebtn').addEventListener('click', function () {
        this.style.display = 'none'
        $$('.stopbtn').style.display = 'none';
        $$('.pausebtn').style.display = 'flex';

        //开启计时器
        timer = setInterval(running, 1000)
    })

    /**
     * 结束
     */
    $$('.stopbtn').addEventListener('click', function () {
        //保存运动数据
        const params = {
            type: 0, //跑步
            duration: t,
            calorie: calCalorie(t * 2),
            meter: t * 2
        }

        //发请求
        axios.post('/api/exercise/save', params).then(function (res) {
            if (res.data.errno === 0) {
                location.href = './running.html'
            }
        })
    })

})
